import re
import csv
import os
import sys

def verify_dict_keys(all_results):
    if not all_results:
        return True
    
    # 获取第一个文件的键作为基准
    first_keys = set(next(iter(all_results.values())).keys())
    
    # 检查每个文件的键是否与基准相同
    for folder, results in all_results.items():
        current_keys = set(results.keys())
        if current_keys != first_keys:
            print(f"错误：文件夹 '{folder}' 的键与其他文件不一致")
            print(f"预期的键: {first_keys}")
            print(f"实际的键: {current_keys}")
            return False
    return True

def process_log(log_file):
    time_dict = {}
    diff_dict = {}
    
    # 读取并处理原始数据
    with open(log_file, 'r') as file:
        for line in file:
            match = re.search(r'(\d+)\s*ns\s*::pstime_measurement::\s*(.*)', line.strip())
            if match:
                time_value = int(match.group(1))
                description = match.group(2).strip().replace(' ', '_')
                time_dict[description] = time_value
    
    # 计算时间差值
    keys = list(time_dict.keys())
    for i in range(1, len(keys)):
        current_key = keys[i]
        prev_key = keys[i-1]
        time_diff = time_dict[current_key] - time_dict[prev_key]
        new_key = f"latency_from_{prev_key}_to_{current_key}"
        diff_dict[new_key] = time_diff
    
    return diff_dict

def process_all_folders():
    base_dir = os.path.dirname(os.path.abspath(__file__))
    all_results = {}
    
    # 遍历所有文件夹
    for folder in os.listdir(base_dir):
        folder_path = os.path.join(base_dir, folder)
        if os.path.isdir(folder_path):
            log_file = os.path.join(folder_path, 'vrun.log')
            if os.path.exists(log_file):
                # 处理该文件夹中的vrun.log
                results = process_log(log_file)
                all_results[folder] = results
    
    # 验证所有文件的键是否一致
    if not verify_dict_keys(all_results):
        print("处理终止：不同文件的键不一致")
        sys.exit(1)
    
    # 将所有结果保存到CSV文件
    with open('all_latency_results.csv', 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        # 写入文件夹名称作为第一列的表头
        headers = ['Folder'] + list(next(iter(all_results.values())).keys())
        writer.writerow(headers)
        # 写入每个文件夹的数据
        for folder, results in all_results.items():
            row = [folder] + list(results.values())
            writer.writerow(row)

if __name__ == "__main__":
    process_all_folders()
    print("所有文件夹的结果已保存到 all_latency_results.csv 文件中")